package com.xiangyun.xyojbackendcommon.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

@Component
@ConfigurationProperties(prefix = "jwt")
public class JwtUtils {

    private String secret;
    private long expiration;


    public String generateToken(String id,String userAccount,String userRole){
        Map<String,Object> claims = new HashMap<>();
        claims.put("id",id);
        claims.put("userAccount",userAccount);
        claims.put("userRole",userRole);
        return createToken(claims);
    }

    private String createToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + expiration))
                .signWith(SignatureAlgorithm.HS256,secret)
                .compact();
    }

    public boolean validateJwt(String token){
        try {
            Jwts.parser().setSigningKey(secret)
                    .parseClaimsJwt(token);
            return true;
        }catch (Exception e){
            return false;
        }
    }

    public String getIdFromToken(String token){
        return getClaimFromToken(token, claims -> claims.get("id",String.class));
    }

    public String getUserAccountFromToken(String token){
        return getClaimFromToken(token, claims -> claims.get("userAccount",String.class));
    }

    public String getUserRoleFromToken(String token){
        return getClaimFromToken(token, claims -> claims.get("userRole",String.class));
    }

    public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver){
        final Claims claims = getAllClaimsFromToken(token);
        return claimsResolver.apply(claims);
    }

    private Claims getAllClaimsFromToken(String token) {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJwt(token)
                .getBody();
    }
}
